package it.secse.idmadaption.plugin.util;

import org.apache.axis2.AxisFault;
import org.apache.axis2.client.Options;
import org.apache.ws.security.WSPasswordCallback;
import org.tempuri.CredentialProviderServiceStub;
import org.tempuri.CredentialProviderServiceStub.GetSecurityToken;
import org.tempuri.CredentialProviderServiceStub.GetSecurityTokenResponse;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;

import java.io.IOException;

public class PWCBHandlerClient implements CallbackHandler {

    public void handle(Callback[] callbacks) throws IOException,
            UnsupportedCallbackException {
        for (int i = 0; i < callbacks.length; i++) {
            
            //When the server side need to authenticate the user
            WSPasswordCallback pwcb = (WSPasswordCallback)callbacks[i];
            
//            if (pwcb.getUsage() == WSPasswordCallback.USERNAME_TOKEN_UNKNOWN) {
//                if(pwcb.getIdentifer()!=null && pwcb.getPassword()!=null) {
//                	Credential.getInstance().setEmail(pwcb.getIdentifer());
//                	Credential.getInstance().setPassword(pwcb.getPassword());
//                	return;
//                } else {
//                    throw new UnsupportedCallbackException(callbacks[i], "check failed");
//                }
//            }
            
            //When the client requests for the password to be added in to the 
            //UT element
//           	try{
//            
//            CredentialProviderServiceStub client = new CredentialProviderServiceStub();
//        	// increase timeout
//        	Options opts= client._getServiceClient().getOptions();
//        	opts.setTimeOutInMilliSeconds(300000);
//        	    	
//        	// create security token request & set callback data
//        	GetSecurityToken token = new CredentialProviderServiceStub.GetSecurityToken();
//        	
//			token.setCallbackAddress("http://" + "127.0.0.1" + ":8015/clientcallback");
//			token.setServiceAddress("http://schemas.google.com/gCal/2005#editor");
//			token.setDelegatee("secsecalendar@gmail.com");
//			token.setDelegator("gianluca.ripa@gmail.com");
//						       	
//        	// get security token
//        	GetSecurityTokenResponse response = client.GetSecurityToken(token);
//        	CredentialProviderServiceStub.UsernameTokenType us = response.getGetSecurityTokenResult().getUsernameToken();
//        	System.out.println(us.getUsername());
//           	} catch(AxisFault e) {
//           		e.printStackTrace();
//           	}
        	
           	
            pwcb.setPassword(CredentialData.getInstance().getPassword());
        }
    }

}

